package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.UserGetLoginDto;
import com.cskaoyan.mall.commons.util.Md5Utils;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

/**
 * @Aurhor: 帅的一批
 * @CreateAt: 2022/10/25 17:23
 * @Description:
 * @PACKAGE_NAME： com.cskaoyan.user.service.impl
 */

@Service
public class LoginServiceImpl implements ILoginService {


    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUserName());
        Member member = memberMapper.selectOneByExample(example);

        //用户不存在
        if (member == null) {
            throw new BizException(UserRetCode.USER_NOT_EXIST_ERRROR.getCode(),
                    UserRetCode.USER_NOT_EXIST_ERRROR.getMessage());
        } else {
            //密码错误
            if (!member.getPassword().equals(Md5Utils.getMd5(request.getUserPwd()))) {
                throw new BizException(UserRetCode.USERORPASSWORD_ERRROR.getCode(),
                        UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            }
            //用户未激活
            if ("N".equals(member.getIsVerified())) {
                throw new BizException(UserRetCode.USER_ISVERFIED_ERROR.getCode(),
                        UserRetCode.USER_ISVERFIED_ERROR.getMessage());
            }
        }
        UserLoginResponse converter = userConverterMapper.converter(member);

        //将json数据放入token中
        UserGetLoginDto userGetLoginDto = new UserGetLoginDto(member.getId(), member.getUsername());
        String s = JSON.toJSONString(userGetLoginDto);
        converter.setToken(JwtTokenUtils.builder().msg(s).build().creatJwtToken());
        return converter;
    }
}
